<template>
  <div class="create-demand-dialog">
    <MyDialog
      :show="isApplyDemand"
      customName="create-demand-dialog"
      dialogWidth="700px"
      @beforeClose="beforeClose"
    >
      <template #body>
        <el-form
          :rules="rulesForm"
          :model="demandForm"
          label-width="110px"
          size="small"
          ref="createDemandForm"
        >
          <el-tabs
            v-model="demandForm.subType"
            @tab-click="changeSubType"
          >
            <el-tab-pane label="空窍申请" name="7" key='7'></el-tab-pane>
            <el-tab-pane label="档案上收" name="8" key='8'></el-tab-pane>
            <el-tab-pane label="空窍回收" name="9" key='9'></el-tab-pane>
          </el-tabs>

          <div class="front-box" v-if="!goNext && demandForm.subType == 7">
            <div class="notice-box">
              <div class="title">装箱须知</div>
              <div class="tip">1、云窍箱内档案不能超宽超高,每箱限重 15kg；</div>
              <div class="tip">
                2、封条请在云窍箱上指示处正确粘贴(如您选择的套餐内没有封条请忽略此条)；
              </div>
              <div class="tip">
                3、装箱时如有云窍箱体损坏,请保存等窍楚人员上收档案时一并带回；
              </div>

              <div class="tip">
                4、云窍箱内有该窍的身份芯片，请务必妥善保管云窍箱。如发现丢失或非箱体本身质量问题而产生的损坏，需
                按15元/个赔偿；
              </div>
              <div class="tip">
                5、每只云窍箱请配备标签表，标签表模板见
                 <a class="go" :underline="false" href='/tag.xls'>附件</a>
                ，如需电子档模板表请添加客服微信或拨打客服热线18014702925。
              </div>
            </div>
            

            <div class="next-box">
              <!-- <div class="left">
                <img src="@/assets/images/form/qr-code.png" alt="窍楚官网" />
                <i class="el-icon-back"></i>
                <div class="tip-text">
                  <p>扫码关注窍楚档案</p>
                  <p>微信公众号</p>
                </div>
              </div> -->
              <div class="left">
                <img src="@/assets/images/form/qr-wx.png" alt="窍楚档案微信公众号" />
                <img src="@/assets/images/form/qr-xcx.png" alt="窍楚+小程序" />
                <img src="@/assets/images/form/qr-kf.png" alt="窍楚客服微信" />
              </div>
              <div class="right">
                <div class="check-box">
                  <el-checkbox v-model="checked"> 我已阅读同意遵守 </el-checkbox>
                </div>
                <el-button
                  type="primary"
                  :disabled="!checked"
                  size="small"
                  @click="goNext = true"
                  class="next-btn"
                >
                  下一步
                </el-button>
              </div>
            </div>
          </div>
          <div v-if="goNext || demandForm.subType != 7" class="table-in-box" >
            <!-- <el-row>
              <el-col :span="12">
                <el-form-item prop="subType" label="创建需求类型">
                  <el-select
                    v-model="demandForm.subType"
                    placeholder="请选择需求类型"
                    @change="changeSubType"
                  >
                    <el-option
                      v-for="item in demandSubType"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row> -->

            <el-row>
              <el-col :span="12">
                <!-- :label="boxTitle + '类型'" -->
                <el-form-item prop="boxType" label="窍类型" >
                  <el-select
                    v-model="demandForm.boxType"
                    placeholder="请选择窍类型"
                  >
                    <el-option
                      v-for="item in boxType"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="contactName" label="联系人">
                  <el-input
                    placeholder="请输入联系人"
                    v-model="demandForm.contactName"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item prop="boxAmount" :label="boxTitle + '数量'">
                  <el-input
                    placeholder="请输入空窍数量"
                    v-model="demandForm.boxAmount"
                    clearable
                    type='number'
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="contactMobile" label="联系方式">
                  <el-input
                    placeholder="请输入联系方式"
                    v-model="demandForm.contactMobile"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
              <!-- </el-row> -->

              <!-- <el-row> -->
              <el-col :span="12" v-if="demandForm.subType == 7">
                <el-form-item prop="expectedTime" label="期望送达">
                  <el-date-picker
                    v-model="demandForm.expectedTime"
                    type="date"
                    placeholder="选择期望送达时间"
                    :clearable="false"
                    :picker-options="forbiddenTime"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="riseTime" label="预计上收">
                  <el-date-picker
                    v-model="demandForm.riseTime"
                    type="date"
                    placeholder="选择预计上收时间"
                    :clearable="false"
                    :picker-options="forbiddenTime"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <!-- </el-row> -->

              <!-- <el-row> -->
              <el-col :span="12">
                <el-form-item prop="parentMobile" label="绑定账号">
                  <el-input
                    placeholder="请输入账号"
                    v-model="demandForm.parentMobile"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="demandForm.subType == 7">
                <el-form-item prop="isIotTrust" label="是否存证">
                  <el-radio-group v-model="demandForm.isIotTrust">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row v-if="demandForm.subType == 8">
              <el-col :span="12">
                <el-form-item prop="operationArea" :label="'操作方式'">
                  <el-select
                    v-model="demandForm.operationArea"
                    placeholder="请选择操作方式"
                  >
                    <el-option
                      v-for="item in operationAreaType"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="userBoxType" :label="'用户窍类型'">
                  <el-select
                    v-model="demandForm.userBoxType"
                    placeholder="请选择用户窍类型"
                  >
                    <el-option
                      v-for="item in userBoxType"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row v-if="demandForm.subType == 8">
              <el-col :span="12">
                <el-form-item prop="isCloudReg" label="是否云登记">
                  <el-radio-group v-model="demandForm.isCloudReg">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="isPacked" label="是否装箱">
                  <el-radio-group v-model="demandForm.isPacked">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <!-- 打包至线上注释， 私有化展示  淮安专有 -->
              <el-col :span="12" v-if="isPrivateLocal">
                <el-form-item prop="isNeedCheck" label="是否需要核对">
                  <el-radio-group v-model="demandForm.isNeedCheck">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="demandForm.subType == 8 && demandForm.boxType == 5">
                <el-form-item prop="isOnRack" label="是否需要容器">
                  <el-radio-group v-model="demandForm.isOnRack">
                    <el-radio :label="0">是</el-radio>
                    <el-radio :label="1">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 打包至线上注释，私有化展示 淮安 isNeedCheck可为1 -->
            <el-row>
              <el-col :span="24" v-if="demandForm.subType == 8 && demandForm.isNeedCheck == 1">
                <el-form-item label="核对标签表格">
                  <el-upload
                    class="upload-demo"
                    action
                    ref="createDemand"
                    :http-request="param => modeUpload(param, 'label')"
                    :before-upload="param => beforeUpload(param, 'label')"
                    :on-change="handleTopImageSuccess"
                    :file-list="fileList"
                    :on-remove="handleRemove"
                    :limit="1"
                  >
                    <el-button type="info" size="small" round
                      >选择核对标签表格</el-button
                    >
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24" v-if="demandForm.subType == 8">
                <el-form-item label="上传文件">
                  <el-button type="info" size="small" round v-if="isShowRemind" @click="showRemind">选择附件</el-button>
                  <el-upload
                    v-else
                    class="upload-demo"
                    action
                    ref="createDemand"
                    :http-request="param => modeUpload(param, 'file')"
                    :before-upload="param => beforeUpload(param, 'file')"
                    :on-change="handleTopImageSuccess"
                    :file-list="fileList"
                    :on-remove="handleRemove"
                    :limit="5"
                  >
                    <el-button type="info" size="small" round
                      >选择附件</el-button
                    >
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="20">
                <el-form-item prop="addressId" :label="addressTitle">
                  <el-select
                    v-model="demandForm.addressId"
                    placeholder="请选择地址"
                  >
                    <el-option
                      v-for="item in addressList"
                      :key="item.id"
                      :label="item.fullArea+item.address"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <div class="add-address-btn">
                  <el-button type="text" @click="showAddAddress" size="mini">
                    <i class="el-icon-plus"></i>添加地址</el-button
                  >
                </div>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item prop="comments" label="注意事项">
                  <el-input
                    type="textarea"
                    placeholder="其他需要窍楚特别注意事项"
                    v-model="demandForm.comments"
                    clearable
                    :rows="3"
                    maxlength="120"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </template>
      <div slot="title">
        <div class="dialog-title">创建需求</div>
      </div>
      <div slot="footer" v-if="goNext || demandForm.subType != 7">
        <span>
          <el-button size="small" @click="applyClose">取 消</el-button>
          <el-button
            size="small"
            type="primary"
            :loading="btnLoading"
            @click="demandConfirm('createDemandForm')"
            >提交</el-button
          >
        </span>
      </div>
    </MyDialog>

    <AddressEdit
      :isShowAddAddress="isShowAddAddress"
      title="添加地址"
      @closeDialog="closeAddressDialog"
    />

    <UploadRemind :visible="dialogVisible" @close="handleClose" @submit="handleSubmit" :info="info"></UploadRemind>
  </div>
</template>

<script>
import { getRemindInfo } from '@/api/access-manage/index'
import UploadRemind from '@/components/uploadRemind.vue';

import { checkPhone } from "../../../utils/common";
import { demandSubType, boxType, operationAreaType, userBoxType } from "../../../utils/dictionary.js";

import AddressEdit from "../../access-manage/components/AddressEdit";

import { toUploadFile } from "../../../api/access-manage/index";
import { applyDemandOrder, getbindMobile } from "../../../api/demand-manage/index";
import { getAddressList } from "../../../api/member/address";

export default {
  name: "ApplyReadDialog",
  props: {
    isApplyDemand: {
      type: Boolean,
      default: false,
    },
    userInfo: {
      type: Object,
      default: () => {},
    },
  },
  components: { AddressEdit, UploadRemind },
  watch: {
    isApplyDemand() {
      if (this.isApplyDemand) {
        if (this.isPrivateLocalF) {
          this.judgeShowRemind()
          this.isShowRemind = true
        }
        

        this.getbindMobile()
        this.demandForm = {
          ...this.demandForm,
          subType: "7",
          boxType: 2,
          expectedTime: Date.now() + 8.64e7,
          riseTime: Date.now() + 8.64e7,
          isIotTrust: 0,
          isCloudReg: 0,
          isPacked: 0,

          contactName: this.userInfo.realName,
          contactMobile: this.userInfo.mobile,
          // parentMobile: this.userInfo.mobile,

          operationArea: 0,
          userBoxType: 0,
          isNeedCheck: 0,
          isOnRack: 0
        };
        this.getAddressList();
      } else {
        this.demandForm = {
          subType: "7",
          contactName: "",
          contactMobile: "",
          parentMobile: "",
          parentUserId: "",
          isCloudReg: 0,
          isPacked: 0,
          operationArea: 0,
          userBoxType: 0,
          isNeedCheck: 0,
          isOnRack: 0
        };
        this.uploadFileList = [];
        this.goNext = false;
        this.checked = false;
      }
    },
  },
  data() {
    return {
      info: '上传附件提醒',
      dialogVisible: false, // 上传附件提示框
      isShowRemind: false,

      isPrivateLocal: process.env.VUE_APP_LOCAL == 'huaian',
      isPrivateLocalF: process.env.VUE_APP_LOCAL == 'fangshan',
      //    
      forbiddenTime: {
        //禁用当前日期之前的日期
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      checked: false,
      goNext: false,
      demandSubType: demandSubType,
      operationAreaType: operationAreaType, // 上收操作地点
      userBoxType: userBoxType, //用户窍类型
      boxType: boxType,
      addressTitle: "送达地址",
      boxTitle: "空窍",

      btnLoading: false,
      fileList: [],

      uploadFileList: [],
      // filePathList: [],
      isShowAddAddress: false,

      addressList: [],

      demandForm: {
        subType: "7",
        boxType: 2,
        boxAmount: "",

        contactName: "",
        contactMobile: "",

        expectedTime: new Date(),
        riseTime: new Date(),

        parentMobile: "",
        parentUserId: "",
        isIotTrust: 0,
        isPacked: 0,
        isCloudReg: 0,
        addressId: "",

        comments: "",
      },
      rulesForm: {
        subType: { required: true, message: "请选择需求类型" },

        boxType: { required: true, message: "请选择窍类型" },
        boxAmount: [
          { required: true, message: "请输入窍数量" },
          { validator: (rule, value, callback) => {
            if (value<=0) {
              return callback(new Error("请填写正确的窍数量"));
            } else {
              callback()
            }
          }, trigger: ["blur", "change"] }
        ],

        expectedTime: { required: true, message: "请选择期望送达时间" },
        riseTime: { required: true, message: "请选择预计上收时间" },

        // uploadFile: { required: true, message: "请选择上传附件" },

        contactName: [{ required: true, message: "请输入联系人" }],
        contactMobile: [
          { required: true, message: "请输入联系方式" },
          { validator: checkPhone, trigger: ["blur", "change"] },
        ],
        parentMobile: [
          { required: true, message: "请填写账户手机号" },
          { validator: checkPhone, trigger: ["blur", "change"] },
        ],

        addressId: [{ required: true, message: "请选择地址" }],
      },
    };
  },

  methods: {
    // 调用接口，判断是否需要展示提示按钮， 有值,将值复制到框里
    judgeShowRemind() {
      // 接口
      getRemindInfo().then(res => {
        this.info = res.data
        if(res.data == null) {
          this.isShowRemind = false
        }
      })

    },
    // 展示上传文件提示框
    showRemind() {
      this.dialogVisible = true
    },
    handleSubmit() {
      this.dialogVisible = false
      this.isShowRemind = false
    },
    handleClose() {
      this.dialogVisible = false
    },


    // 获得绑定账号
    getbindMobile() {
      new Promise((resolve) => {
        getbindMobile().then(res => {
          this.demandForm.parentMobile = res.data?.mobile
          this.demandForm.parentUserId = res.data?.id          
        })
      })
    },
    // 需求类型改变
    changeSubType() {
      if (this.demandForm.subType == 9) {
        //   空窍回收
        this.addressTitle = "回收地址";
        this.boxTitle = "空窍";
      }
      if (this.demandForm.subType == 8) {
        //  档案上收
        this.addressTitle = "操作地址";
        this.boxTitle = "上收窍";
        this.demandForm.isPacked = 0;
        this.demandForm.isCloudReg = 0;
      }
      if (this.demandForm.subType == 7) {
        //  空窍申请
        this.addressTitle = "送达地址";
        this.boxTitle = "空窍";
      }

      this.$forceUpdate();
    },
    // 新增地址弹窗
    closeAddressDialog() {
      this.isShowAddAddress = false;
      this.getAddressList();
    },
    // 展开添加地址弹窗
    showAddAddress() {
      this.isShowAddAddress = true;
    },

    // 文件上传
    modeUpload(param, type) {
      param['fileType'] = type
      this.uploadFileList.push(param);
      this.toUploadFile(param);
    },
    // 文件移除
    handleRemove(file, fileList) {
      // 从this.uploadFileList移除
      let list = [];
      this.uploadFileList.map((e) => {
        if (e.file.uid != file.uid) {
          list.push(e);
        }
      });
      this.uploadFileList = list;
      // this.toUploadFile();
    },
    // 上传文件限制
    beforeUpload(file, type) {
      // 限制文件最大为10MB
      const isLt10M = file.size / 1024 / 1024 <= 10;
      if(!isLt10M) {this.$message.warning('上传文件大小不能超过 10MB!');}

      // this.uploadFileList 中 已有此文件 则 返回 false
      let isRepeat = this.uploadFileList.filter(e => e.file.name == file.name && e.fileType == type).length > 0
      if (isRepeat) {this.$message.warning('上传文件重复');}

      return isLt10M && !isRepeat;
    },
    // 上传成功后
    handleTopImageSuccess() {
      // this.$refs.uploadButton.submit();
      // // 确定上传后需 清空文件 否则会多次上传
      // this.$refs.uploadButton.clearFiles();
    },

    // 关闭调阅窗口
    beforeClose() {
      this.$emit("closeApplyDialog");
    },
    // 取消按钮 - 关闭表单
    applyClose() {
      this.$emit("closeApplyDialog");
    },
    //  上传文件附件
    toUploadFile(param) {
      let formData = new FormData();
      // this.uploadFileList.map((e) => {
      //   formData.append("file", e.file);
      // });
      formData.append("file", param.file);
      // if (this.uploadFileList.length == 0) {
      //   this.filePathList= []
      //   return 
      // }
      // { id: 0 }
      toUploadFile(formData)
        .then((res) => {
          if (res.code == 200) {
            // this.filePathList = res.data;
            this.uploadFileList.filter(m => m.file.uid == param.file.uid)[0]['path'] = res.data[0]
          }
        })
        .catch((err) => {
          // this.isLoading = false;
        });
    },
    // 创建需求 表单提交
    demandConfirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.uploadFileList.filter(c => !c.path).length > 0) {
            this.$message.info("请等待附件上传完成后提交");
            return
          }
          this.btnLoading = true;

          // this.uploadFileList.length > 0 && this.toUploadFile();
          let addressSelected = this.addressList.filter(
              (e) => e.id == this.demandForm.addressId
            )[0]
          
          // 获得路径url
          const urlArr = []
          const labelFile = []
          this.uploadFileList.map(m => {
            if (m.fileType == 'file') {
              urlArr.push(m.path)
            } else if (m.fileType == 'label') {
              labelFile.push(m.path)
            }
          })
          const data = {
            ...this.demandForm,
            boxAmount: Number(this.demandForm.boxAmount),
            // this.demandForm.subType == 8 && this.demandForm.operationArea == 1 ? null :
            address: addressSelected.fullArea + addressSelected.address,

            expectedTime: this.demandForm.subType == 7 ? parseInt(
              this.$moment(this.demandForm.expectedTime).valueOf() / 1000
            ): null,
            riseTime: parseInt(
              this.$moment(this.demandForm.riseTime).valueOf() / 1000
            ),

            filePathList: urlArr,
            // this.filePathList,
            checkTagPathList: labelFile, // 被核对标签表格
          };

          new Promise((resolve) => {
            applyDemandOrder(data)
              .then((res) => {
                this.btnLoading = false;
                this.$message({
                  type: "success",
                  message: "申请成功",
                });
                this.$emit("closeApplyDialog");
                this.$emit("getList");
              })
              .catch((err) => {
                this.btnLoading = false;
                this.$emit("closeApplyDialog");
              });
          });
        }
      });
    },
    // 获得地址列表
    getAddressList() {
      getAddressList().then((res) => {
        this.addressList = res.data;
        let oneArray = res.data.filter(e => e.isDefault == 1)
        this.demandForm.addressId = oneArray && oneArray[0]?.id
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.create-demand-dialog {
  .dialog-title {
    color: #f88123;
    font-size: 16px;
  }
  .more-box-show {
    background: #eee;
    color: #f88123;
    padding-left: 10px;

    .selected-list {
      max-height: 200px;
      overflow-y: scroll;
    }
  }
  .show-more {
    color: #f88123;
    padding-left: 18px;
    margin-bottom: 10px;
    line-height: 30px;
    .more {
      width: 120px;
      cursor: pointer;
    }
  }
}

.address-list {
  ::v-deep  .el-radio-group {
    display: flex;
    flex-direction: column;
    height: 100px;
    overflow-y: scroll;
    .el-radio {
      display: flex;
      align-items: center;
      margin: 5px 0;
      .address-item {
        span {
          margin-right: 10px;
        }
      }
    }
  }
}
.add-address-btn {
  padding-left: 15px;
}

.on-time {
  font-size: 10px;
}

.create-demand-dialog {
  ::v-deep .el-select,
  .el-input {
    width: 100%;
  }
}

.front-box {
  .notice-box {
    padding: 10px 20px 10px 25px;
    border: 1px solid #f88123;
    margin:  0 20px;
    .title {
      text-align: center;
      line-height: 30px;
      font-weight: bold;
    }
    .tip {
      line-height: 20px;
      margin: 10px 0;
      .go {
        color:#f88123;
        position: relative;
        top: -2px;
      }
    }
  }

 
  .next-box {
    display: flex;
    justify-content: space-between;
    // align-items: flex-end;
    margin: 35px 20px 10px;

    .left {
      display: flex;
      align-items: flex-end;
      img {
        width: 92px;
        margin-right: 38px;
      }
      i {
        font-size: 20px;
        margin: 0 10px 20px;
      }
      .tip-text {
        font-size: 12px;
        margin-bottom: 8px;
      }
    }
    .right {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: flex-end;
      .check-box {
        // margin: 18px 0;
        text-align: center;
      }
      .next-btn {
        width: 80px;
      }
    }
  }
}

.table-in-box {
  min-height: 34px;
}

// 样式调整
::v-deep .el-tabs__header {
  margin-bottom: 25px;
}
</style>
